//
//  ISDUETRotaryWheel.m
//  12Cung
//
//  Created by Tran Bao Thai on 8/4/12.
//  Copyright (c) 2012 Tran Bao Thai. All rights reserved.
//

#import "ISDUETRotaryWheel.h"
#import "ISDUETSector.h"
#import <QuartzCore/QuartzCore.h>
#import "Constants.h"

@interface ISDUETRotaryWheel()
- (void) drawWheel;
- (float) calculateDistanceFromCenter:(CGPoint)point;
- (void) buildSectorsEven;
- (void) buildSectorsOdd;
- (UIImageView*) getSectorImageByValue:(int)value;
- (NSString*) getSectorName:(int)position;
@end

static float deltaAngle;

@implementation ISDUETRotaryWheel

@synthesize wheelDelegate, containerView, numberOfSection, sectorArr, startTransform, currentValue;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id) initWithFrame:(CGRect)frame andDelegate:(id)aDelegate withSections:(int)sectionsNumber{
    self = [super initWithFrame:frame];
    if (self) {
        self.currentValue = 0;
        self.numberOfSection = sectionsNumber;
        self.wheelDelegate = aDelegate;
        [self drawWheel];
    }
    return self;
}

- (void) drawWheel{
    containerView = [[UIView alloc]initWithFrame:self.frame];
    
    CGFloat angleSize = 2*M_PI/numberOfSection;
    for (int i = 0; i < numberOfSection; i++) {
        UIImageView* segmentImgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"14segment"]];
        segmentImgV.layer.anchorPoint = CGPointMake(1.0f, 0.5f);
        segmentImgV.layer.position = CGPointMake(containerView.bounds.size.width/2.0 - containerView.frame.origin.x,containerView.bounds.size.height/2.0 - containerView.frame.origin.y);
        segmentImgV.transform = CGAffineTransformMakeRotation(angleSize*i);
        segmentImgV.alpha = MIN_ALPHA;
        segmentImgV.tag = i;
        
        if (i == 0) {
            segmentImgV.alpha = MAX_ALPHA;
        }
        
        UIImageView* sectorImgV = [[UIImageView alloc]initWithFrame:CGRectMake(12, 15, 40, 40)];
        sectorImgV.image =[UIImage imageNamed:[NSString stringWithFormat:@"iSector%i.png", i]];
        [segmentImgV addSubview:sectorImgV];
        [sectorImgV release];
        
        [containerView addSubview:segmentImgV];
        [segmentImgV release];
    }
    
    containerView.userInteractionEnabled = NO;
    [self addSubview:containerView];
    
    sectorArr = [[NSMutableArray alloc]initWithCapacity:numberOfSection];
    /*
    UIImageView* backgroundImgV = [[UIImageView alloc] initWithFrame:self.frame];
    backgroundImgV.image = [UIImage imageNamed:@"wheelBackground_iPhone"];
    [self addSubview:backgroundImgV];
    [backgroundImgV release];
    */
    /*
    UIImageView* mask = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 58, 58)];
    mask.image = [UIImage imageNamed:@"centerButton.png"];
    mask.center = self.center;
    mask.center  = CGPointMake(mask.center.x, mask.center.y +3);
    [self addSubview:mask];
    [mask release];
    */
     
    if (numberOfSection%2 == 0) {
        [self buildSectorsEven];
    } else {
        [self buildSectorsOdd];
    }
    
    [self.wheelDelegate wheelDidChangeValue:[self getSectorName:currentValue] withCurrentSector:currentValue];
}

- (float) calculateDistanceFromCenter:(CGPoint)point{
    CGPoint selfCenter = CGPointMake(self.bounds.size.width/2.0f, self.bounds.size.height/2.0f);
    float dx = point.x - selfCenter.x;
    float dy = point.y - selfCenter.y;
    return sqrtf(dx*dx + dy*dy);
}

- (void) buildSectorsEven{
    CGFloat fanWidth = M_PI*2/numberOfSection;
    CGFloat middle = 0;
    for (int i = 0;  i < numberOfSection; i++) {
        ISDUETSector* sector = [[ISDUETSector new]autorelease];
        sector.middleValue = middle;
        sector.minValue = middle - (fanWidth/2);
        sector.maxValue = middle + (fanWidth/2);
        sector.value = i;
        
        if (sector.maxValue - fanWidth < - M_PI) {
            middle = M_PI;
            sector.middleValue = middle;
            sector.minValue = fabs(sector.maxValue);
        }
        
        middle -= fanWidth;
        [sectorArr addObject:sector];
        //[sector release];
    }
    NSLog(@"NUMBER: %i", [sectorArr count]);
}

- (void) buildSectorsOdd{
    CGFloat fanWidth = M_PI*2/numberOfSection;
    CGFloat middle = 0;
    
    for (int i = 0; i < numberOfSection; i++) {
        ISDUETSector* sector = [[ISDUETSector alloc]init];
        sector.middleValue = middle;
        sector.minValue = middle - (fanWidth/2);
        sector.value = i;
        
        if (sector.minValue < - M_PI) {
            middle -= middle;
            middle -= fanWidth;
        }
        
        [sectorArr addObject:sector];
        [sector release];
    }
}

- (UIImageView*) getSectorImageByValue:(int)value{
    UIImageView* result;
    NSArray* subViews = [containerView subviews];
    
    for (UIImageView* imgV in subViews) {
        if (imgV.tag == value) {
            result = imgV;
        }
    }
    
    return result;
}

- (NSString*) getSectorName:(int)position{
    NSString* result = @"";
    switch (position) {
        case 0:
        {
            result = @"Tử vi hàng ngày";
            break;
        }
        case 1:
        {
            result = @"Tin tức";
            break;
        }
        case 2:
        {
            result = @"12 Cung Hoàng Đạo";
            break;
        }
        case 3:
        {
            result = @"Giới thiệu";
            break;
        }
        default:
            break;
    }
    return result;
}

- (BOOL) beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    CGPoint touchPoint = [touch locationInView:self];
    
    float distance = [self calculateDistanceFromCenter:touchPoint];
    if (distance< 40 || distance > 160) {
        return NO;
    }
    
    float dx = touchPoint.x - containerView.center.x;
    float dy = touchPoint.y - containerView.center.y;
    deltaAngle = atan2(dy, dx);
    
    startTransform = containerView.transform;
    
    UIImageView* imgV = [self getSectorImageByValue:currentValue];
    imgV.alpha = MIN_ALPHA;
    
    return YES;
    
}

- (BOOL) continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    CGPoint touchPoint = [touch locationInView:self];
    
    float distance = [self calculateDistanceFromCenter:touchPoint];
    if (distance< 40 || distance > 160) {
        return NO;
    }
    
    float dx = touchPoint.x - containerView.center.x;
    float dy = touchPoint.y - containerView.center.y;
    float angle = atan2(dy, dx);
    
    float angleDifference = deltaAngle - angle;
    containerView.transform = CGAffineTransformRotate(startTransform, - angleDifference);
    return YES;
}

- (void) endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    CGFloat radians = atan2f(containerView.transform.b, containerView.transform.a);
    CGFloat newValue = 0.0;
    for (ISDUETSector* sector in sectorArr) {
        if (sector.minValue > 0 && sector.maxValue < 0) {
            if (sector.maxValue > radians || sector.minValue < radians) {
                if (radians > 0) {
                    newValue = radians - M_PI;
                } else {
                    newValue = M_PI + radians;
                }
                currentValue = sector.value;
            }
        } else if (radians > sector.minValue && radians < sector.maxValue){
            newValue = radians - sector.middleValue;
            currentValue = sector.value;
        }
    }
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    CGAffineTransform transform = CGAffineTransformRotate(containerView.transform, - newValue);
    containerView.transform = transform;
    [UIView commitAnimations];
    
    [self.wheelDelegate wheelDidChangeValue:[self getSectorName:currentValue] withCurrentSector:currentValue];
    
    UIImageView* imgView = [self getSectorImageByValue:currentValue];
    imgView.alpha = MAX_ALPHA;
}

- (void)dealloc{
    //[wheelDelegate release];
    [containerView release];
    [sectorArr release];
    [super dealloc];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
